package com.junzhiit.nengji.cms.interceptor;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.JsonUtil;
import com.junzhiit.nengji.cms.web.util.CMSCodeStatus;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;

@Component
public class SessionInterceptor extends HandlerInterceptorAdapter {

	protected Log logger = LogFactory.getLog(this.getClass().getName());
	
	private final int HOUR = 6;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		ResultVO result = new ResultVO();
		boolean flag = true;
		String sessionId = request.getParameter("sessionId");
		if(StringUtils.isNotBlank(sessionId)){
			ServletContext context = request.getSession().getServletContext();
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
			SystemUserCacheDAO systemUserCacheDAO = (SystemUserCacheDAO) ctx.getBean("systemUserCacheDAOImpl");
			String key = DIYKey.getSessionHashKey(sessionId);
			SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
			if(session!=null){
				if(session.getLogoutTime() != null){
					flag = false;
					result.setStatus(CMSCodeStatus.INVALID_SESSION);
					result.setMessage("Invalid session: Session logout.");
				}
				Date lastAccessTime = DateUtil.getTime(session.getLastAccessTime());
				Long timeout = DateUtil.getDateByHour(lastAccessTime, HOUR).getTime();
				if(new Date().getTime() > timeout){
					flag = false;
					result.setStatus(CMSCodeStatus.SESSION_TIMEOUT);
					result.setMessage("Session timeout.");
					session.setLogoutTime(new Date());
				}
				session.setLastAccessTime(new Date().getTime());
				systemUserCacheDAO.addHash(key, session);
			}else{
				flag = false;
				result.setStatus(CMSCodeStatus.INVALID_SESSION);
				result.setMessage("Invalid session: Session id not find.");
			}
		}else{
			flag = false;
			result.setStatus(CMSCodeStatus.INVALID_SESSION);
			result.setMessage("Invalid session: Session id is required.");
		}
		
		if(!flag){
			response.getWriter().print(JsonUtil.toJson(result));
		}
		return flag;
	}

}
